<!DOCTYPE html>
<html lang="">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
		<link rel="stylesheet" href="../../lib/layui/css/layui.css" media="all">
		<style type="text/css">
			body,
			html {
				width: 100%;
				height: 100%;
				margin: 0;
				font-family: "微软雅黑",serif;
			}
			
			#allmap {
				width: 100%;
				height: 75%;
				overflow: hidden;
			}
			
			#result,#r-result {
				width: 800px;
				margin: 20px auto;
			}
			
			dl,
			dt,
			dd,
			ul,
			li {
				margin: 0;
				padding: 0;
				list-style: none;
			}
			
			p {
				font-size: 12px;
			}
			
			dt {
				font-size: 14px;
				font-family: "微软雅黑";
				font-weight: bold;
				border-bottom: 1px dotted #000;
				padding: 5px 0 5px 5px;
				margin: 5px 0;
			}
			
			dd {
				padding: 5px 0 0 5px;
			}
			
			li {
				line-height: 28px;
			}
			
			label#MapName,
			label.position{
				margin-left: 18px;
				font-size: 18px;
			}
			
			label {
				font-size: 18px;
			}
			
			input.draw,
			input.btn,input.draw,input.clear {
				width: 80px;
				height: 30px;
				margin-right: 20px;
				background: rgb(13, 155, 242);
				border: none;
				color: white;
				cursor: pointer;
				border-radius:6% ;
			}
			
		</style>
		<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=F0i6SrLmHquLVNLCqpExxPrj8mWVdFwx"></script>
		<!--加载鼠标绘制工具-->
		<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
		<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
		<!--加载检索信息窗口-->
		<script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>

		<link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
		<script src="../../lib/layui/layui.all.js"></script>
		<title>添加配送范围</title>
	</head>

	<body>
		<div id="r-result">
			<label class="position" style="margin-left: -15px">位置:</label>&nbsp;&nbsp;&nbsp;&nbsp;
			<input type="text" id="suggestId" size="20" placeholder="请输入关键字搜索确定大致位置" style="width: 350px;height: 35px;" /></div>
		<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
		<div id="result">
			<label id="MapName" style="margin-left: -15px">名称:</label>&nbsp;&nbsp;&nbsp;&nbsp;
			<input type="text" class="MapName" name="MapName" style="width: 350px;height: 35px;"><br><br>

			<div class="layui-input-block" style="margin-left: -15px">
				<div style="margin-left: -30px;">
					<form class="layui-form" action="" >
						<div class="layui-form-item">
							<label class="layui-form-label">颜色值 :</label>
							<div class="layui-input-inline" style="width: 250px;">
								<input class="layui-input" id="test-form-input" name="MapColor" type="text" placeholder="请选择颜色" value="#1c97f5"
									   style="width: 300px">
							</div>
							<div class="layui-inline" style="left: -11px;">
								<div id="test-form" style="width: 150px;height: 50px;margin-left: 50px"></div>
							</div>
						</div>
					</form>
				</div>
			</div>
			<input type="button" class="draw" value="绘制范围" onclick="draw(BMAP_DRAWING_POLYLINE)" onclick="getPoint()" />
			<input type="button" class="clear" value="清除绘制" onclick="remove_overlay()"/>
			<input type="button" class="btn" value="添加范围" />
			<i id="text"></i>
		</div>
		<div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
			<div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">
			</div>
		</div>

		<div id="resultShape"></div>
		<script src="../../lib/jquery-3.3.1.min.js"></script>
		<script src="/lib/iColorPicker.js"></script>
		<!--颜色选择-->
		<script>
			layui.use('layer', function () {
				var layer = layui.layer //弹层
				layui.use('colorpicker', function () {
					var $ = layui.$
							, colorpicker = layui.colorpicker;
					//开启全功能
					colorpicker.render({
						elem: '#test-form'
						, color: '#1c97f5'
						, predefine: true
						, alpha: true
						, done: function (color) {
							$('#test-form-input').val(color);
							layer.tips('给指定隐藏域设置了颜色值：' + color, this.elem);
							color || this.change(color); //清空时执行 change
						}
					});
				})
			});
		</script>
		<script>
            var ScopeName=[];//生成数组用于保存范围的名字
            //生成范围名字按钮
            $(function() {
                jQuery.ajax({
                    url: "/num",
                    type: "post",
                    dataType: "json",
                    success: function(data) {
                        jQuery.each(data,function (k, v) {
                            // jQuery("div#ranges").append(jQuery("<div class='range'>"+v.mapName+"</div>"))
                            ScopeName[k]=v.mapName
                        })
                        getMap();
                    },
                    error: function(e) {
                        console.log(e)
                    }
                })
            })

            var pointXY=[];//声明数组用户存储经纬度
            var color=null;//用于颜色中转
            //点击区域名字获取范围
            function  getMap() {
                jQuery("div.range").on("click",function () {
                    var mName=jQuery(this).text()
                    jQuery.ajax({
                        url: "/map",
                        data:{"MapName":mName},
                        type: "post",
                        dataType: "json",
                        success: function(data) {
                            jQuery.each(data,function (k, v) {
                                if (mName===v.mapName){
                                    var a = v.coordinate.split(',');
                                    pointXY[k] = new BMap.Point(parseFloat(a[0]), parseFloat(a[1]));
                                    color=v.mapColor;
                                }
                            })
                            createScope(pointXY,color)
                        },
                        error: function(e) {
                            console.log(e)
                        }
                    })
                })
                //循环把后端得到的范围名字再传给后端进行寻找对应的经纬度
                var Xy=[];//声明数组用于保存经纬度
                var mc=null;//用于颜色的中转
                for (var i = 0; i <ScopeName.length ; i++) {
                    jQuery.ajax({
                        url:"/show",
                        traditional: true,
                        data:{"mName":ScopeName[i]},
                        type:"post",
                        dataType:"json",
                        success:function (data) {
                            jQuery.each(data,function (k,v) {
                                var a = v.coordinate.split(',');
                                Xy[k] = new BMap.Point(parseFloat(a[0]), parseFloat(a[1]));
                                mc=v.mapColor;
                            })
                            createScope(Xy,mc)
                        },
                        error:function (e) {
                            console.log(e)
                        }
                    })
                }
            }
            //生成范围
            function createScope(point,color) {
                var polygon = new BMap.Polygon(point, {strokeWeight: 2, strokeOpacity: 0.5, fillColor:color});  //创建多边形
                map.addOverlay(polygon);   //增加多边形

                return polygon;
            }
		</script>
		<script>
			//监听输入框的状态,并进行改变背景颜色
			jQuery(function() {
			   /* jQuery("input#test-form-input").bind("input propertychange",function () {
                    jQuery("input#test-form-input").css("background",jQuery("input#test-form-input").val())
                })*/
				//点击按钮添加配送范围
				jQuery("input.btn").on("click", function() {
					var point = [];
					point = getPoint();
					console.log(getPoint())
					// for(var i = 0; i < point.length; i++) {
						jQuery.ajax({
							url: "/insert",
                            traditional: true,
							data: {
								"coordinate": point,
								"MapName": jQuery("input.MapName").val(),
								"MapColor": jQuery("input#test-form-input").val()
							},
							type: "post",
							dataType: "json",
							success: function(data) {
								if (data.stat=="SUCCESS"){
								    jQuery("i#text").css("color","green").html("配送范围添加成功!")
								}else{}
                                jQuery("ii#text").css("color","red").html("配送范围添加失败!")
								// flush();
							},
							error: function(e) {
								console.log(e)
							}
						})
				})

			})
            //刷新
            function flush() {
                location.reload();
            }
		</script>
		<script type="text/javascript">
			// 百度地图API功能
			var map = new BMap.Map('map');
			var poi = new BMap.Point(104.050528,30.556761);
			map.centerAndZoom(poi, 18);
			map.enableScrollWheelZoom();
			var marker = new BMap.Marker(poi); // 创建标注
			map.addOverlay(marker); // 将标注添加到地图中
			marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
            marker.disableMassClear();

			function $(id) {
				return document.getElementById(id);
			}

			var overlays = [];
			var overlaycomplete = function(e) {
				overlays.push(e.overlay);
			};

			var styleOptions = {
				strokeColor: "red", //边线颜色。
				fillColor: "red", //填充颜色。当参数为空时，圆形将没有填充效果。
				strokeWeight: 3, //边线的宽度，以像素为单位。
				strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
				fillOpacity: 0.6, //填充的透明度，取值范围0 - 1。
				strokeStyle: 'solid' //边线的样式，solid或dashed。
				
			}

			//实例化鼠标绘制工具
			var drawingManager = new BMapLib.DrawingManager(map, {
				isOpen: false, //是否开启绘制模式
				//enableDrawingTool: true, //是否显示工具栏
				drawingToolOptions: {
					anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
					offset: new BMap.Size(5, 5), //偏离值
				},
				circleOptions: styleOptions, //圆的样式
				polylineOptions: styleOptions, //线的样式
				polygonOptions: styleOptions, //多边形的样式
				rectangleOptions: styleOptions //矩形的样式
			});

			//添加鼠标绘制工具监听事件，用于获取绘制结果
			drawingManager.addEventListener('overlaycomplete', overlaycomplete);

			map.addEventListener("rightclick", function(e) {
				if(confirm(e.point.lng + "," + e.point.lat)) {
					$("shape").innerHTML = $("shape").innerHTML + " <br/>(" + e.point.lng + "," + e.point.lat + ")";
				}
			});

			function draw(type) {
				drawingManager.open();
				drawingManager.setDrawingMode(type);
			}

			function clearAll() {
				for(var i = 0; i < overlays.length; i++) {
					map.removeOverlay(overlays[i]);
				}
				overlays.length = 0
			}

			function getPoint() {
                var tmp = [];
                for(var i = 0; i < overlays.length; i++) {
                    var overlay = overlays[i].getPath();
                    for(var j = 0; j < overlay.length; j++) {
                        var grid = overlay[j];
                        tmp[j] = (grid.lng + "," + grid.lat)
                    }
                }
                return tmp;
            }

			function Editing(state) {
				for(var i = 0; i < overlays.length; i++) {
					state == 'enable' ? overlays[i].enableEditing() : overlays[i].disableEditing();
				}
			}

			function showPolygon(btn) {
				var polygon = new BMap.Polygon([
					new BMap.Point(104.031297,30.550703),
					new BMap.Point(104.031297,30.550703),
					new BMap.Point(104.031297,30.550703),
					new BMap.Point(104.031297,30.550703)
				], styleOptions); //创建多边形
				map.addOverlay(polygon); //增加多边形
				// overlays.push(polygon); //是否把该图像加入到编辑和删除行列
				btn.setAttribute('disabled', 'false');
				showText();
			}

			function showText() {
				var opts = {
					position: new BMap.Point(104.050528,30.556761), // 指定文本标注所在的地理位置
					offset: new BMap.Size(30, 30) //设置文本偏移量
				}
				var label = new BMap.Label("不可编辑", opts); // 创建文本标注对象
				label.setStyle({
					color: "black",
					fontSize: "16px",
					fillColor: "red", //填充颜色。当参数为空时，圆形将没有填充效果。
				});
				map.addOverlay(label);
			}
			//搜索位置
			function G(id) {
				return document.getElementById(id);
			}

			var ac = new BMap.Autocomplete( //建立一个自动完成的对象
				{
					"input": "suggestId",
					"location": map
				});

			ac.addEventListener("onhighlight", function(e) { //鼠标放在下拉列表上的事件
				var str = "";
				var _value = e.fromitem.value;
				var value = "";
				if(e.fromitem.index > -1) {
					value = _value.province + _value.city + _value.district + _value.street + _value.business;
				}
				str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

				value = "";
				if(e.toitem.index > -1) {
					_value = e.toitem.value;
					value = _value.province + _value.city + _value.district + _value.street + _value.business;
				}
				str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
				G("searchResultPanel").innerHTML = str;
			});

			var myValue;
			ac.addEventListener("onconfirm", function(e) { //鼠标点击下拉列表后的事件
				var _value = e.item.value;
				myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
				G("searchResultPanel").innerHTML = "onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

				setPlace();
			});

			function setPlace() {
				map.clearOverlays(); //清除地图上所有覆盖物
				function myFun() {
					var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
					map.centerAndZoom(pp, 18);
					map.addOverlay(new BMap.Marker(pp)); //添加标注
				}
				var local = new BMap.LocalSearch(map, { //智能搜索
					onSearchComplete: myFun
				});
				local.search(myValue);
			}
			//清除覆盖物
			function remove_overlay(){
				map.clearOverlays();  
			}
		</script>
	</body>

</html>